import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/XTextField/XTextField.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/pages/auth/forgot_password/view.dart';
import 'package:orginone/pages/auth/login_transition/index.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/routers/router_const.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../components/BeautifulBGWidget/BeautifulBGWidget.dart';
import '../../../components/XDialogs/dialog_utils.dart';
import '../../../components/XDialogs/LoadingDialog.dart';
import '../../../components/Tip/ToastUtils.dart';
import '../../../config/constant.dart';
import 'package:orginone/dart/core/public/consts.dart';
import 'package:orginone/dart/base/storages/storage.dart';
import '../../../dart/base/model.dart';
import '../../../main.dart';
import '../components/ClauseWidget/ClauseWidget.dart';
import '../register/view.dart';

class LoginPage extends BeautifulBGStatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends BeautifulBGStatefulState<LoginPage> {
  var accountLogin = true;

  var phoneNumberLogin = false;

  TextEditingController accountController = TextEditingController(text: "");

  TextEditingController passWordController = TextEditingController(text: "");

  TextEditingController phoneNumberController = TextEditingController();

  TextEditingController verifyController = TextEditingController();

  var dynamicId = '';

  var agreeTerms = false;

  var passwordUnVisible = true;

  //是够允许点击登录
  var allowCommit = false;

  var sendVerify = false;

  //验证码输入完成状态
  // var verificationDone = false.obs;
  //验证码重置时间
  var countDown = 60;
  //开始计时
  var startCountDown = false;
  Timer? timer;

  @override
  void initState() {
    super.initState();
    // if (!kernel.isOnline) {
    //   kernel.start();
    // }
    Future.delayed(const Duration(seconds: 0)).then((onValue) async {
      // 条款弹框
      AlertDialogUtils.showPrivacyDialog(context);
    });
    var account = Storage.getList(Constants.account);
    agreeTerms = Storage.getBool('agreeTerms');
    if (account.isNotEmpty) {
      accountController.text = account.first;
      phoneNumberController.text = account.first;
      passWordController.text =
          "" != account.last ? account.last : Constant.pwd;
    } else {
      accountController.text = Constant.userName;
      phoneNumberController.text = Constant.userName;
      passWordController.text = Constant.pwd;
    }
    allowLogin();
  }

  @override
  Widget buildWidget(BuildContext context) {
    return formLayout(context,
        showBack: false,
        showLogo: false,
        form: Padding(
          padding: const EdgeInsets.only(top: 30, left: 30, right: 30),
          child: Column(
            children: [loginTitle(), const SizedBox(height: 30), switchLoginType(), loginForm()],
          ),
        ));
  }

  // 登录标题
  Widget loginTitle() {
    return Container(
      alignment: Alignment.centerLeft,
      child: Text(
        '欢迎来到 奥集能',
        style: TextStyle(fontSize: 28, fontWeight: FontWeight.w600),
      ),
    );
  }

  //切换账号登录和验证码登录类型
  Widget switchLoginType() {
    return SizedBox(
      width: 375,
      height: 50,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          switchTips(accountLogin, '账号登录', 1),
          switchTips(phoneNumberLogin, '手机号登录', 0),
        ],
      ),
    );
  }

  Widget switchTips(bool isChoice, String title, int x) {
    if (isChoice) {
      return GestureDetector(
        onTap: () {
          switchMode(x);
        },
        child: Container(
          width: 102,
          height: 40,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                title,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: Color(0xFF366EF4),
                  fontSize: 14,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w600,
                ),
              ),
              Container(
                width: 16,
                height: 3,
                decoration: ShapeDecoration(
                  color: const Color(0xFF366EF4),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(999),
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    } else {
      return GestureDetector(
        onTap: () {
          switchMode(x);
        },
        child: Container(
          width: 102,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                title,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: Color(0xFF15181D),
                  fontSize: 14,
                  fontFamily: 'PingFang SC',
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        ),
      );
    }
  }

  //登录提交按钮
  Widget loginSubmit() {
    return SizedBox(
      height: 45,
      child: GestureDetector(
        onTap: () {
          if (!agreeTerms) {
            ToastUtils.showMsg(msg: "请阅读并同意服务条款与隐私条款");
            return;
          }
          if (accountLogin) {
            login();
          }
          if (phoneNumberLogin) {
            verifyCodeLogin();
          }
        },
        child: button(XColors.themeColor),
      ),
    );
  }

  Widget button(Color color) {
    double widthBtn = (MediaQuery.maybeOf(context)?.size.width ?? 400) - 70;
    return Container(
        width: widthBtn,
        height: 45,
        alignment: Alignment.center,
        padding: const EdgeInsets.only(top: 12),
        decoration: ShapeDecoration(
          color: color,
          shape: RoundedRectangleBorder(
            side: const BorderSide(width: 1, color: Color(0xFFE7E8EB)),
            borderRadius: BorderRadius.circular(8),
          ),
        ),
        child: const Text(
          '登录',
          textAlign: TextAlign.center,
          style: TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontFamily: 'PingFang SC',
            fontWeight: FontWeight.w600,
            height: 0.09,
          ),
        ));
  }

  //第三方登录按钮
  Widget thirdLoginPlatform() {
    return Container();
    // return Container(
    //   alignment: Alignment.centerLeft,
    //   child: Row(
    //     mainAxisSize: MainAxisSize.min,
    //     mainAxisAlignment: MainAxisAlignment.start,
    //     crossAxisAlignment: CrossAxisAlignment.center,
    //     children: [
    //       Text(
    //         '其他方式',
    //         style: TextStyle(
    //           color: Colors.black.withOpacity(0.6000000238418579),
    //           fontSize: 14,
    //           fontFamily: 'PingFang SC',
    //           fontWeight: FontWeight.w400,
    //         ),
    //       ),
    //       const SizedBox(width: 16),
    //       plantForm(AssetsImages.loginWechat),
    //       const SizedBox(width: 16),
    //       plantForm(AssetsImages.loginZhifubao),
    //       const SizedBox(width: 16),
    //       plantForm(AssetsImages.loginDing),
    //     ],
    //   ),
    // );
  }

  Widget plantForm(
    String icon,
  ) {
    return Container(
      width: 40,
      height: 40,
      clipBehavior: Clip.antiAlias,
      decoration: ShapeDecoration(
        color: Colors.white,
        shape: RoundedRectangleBorder(
          side: const BorderSide(width: 1, color: Color(0xFFDCDCDC)),
          borderRadius: BorderRadius.circular(100),
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            width: 20,
            height: 20,
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(icon),
                fit: BoxFit.fill,
              ),
            ),
          ),
        ],
      ),
    );
  }

  //登录账号密码验证码表单
  Widget loginForm() {
    return (accountLogin)
        ? SizedBox(
            height: 400,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                XTextField.input(
                  onChanged: (value) {
                    allowLogin();
                  },
                  controller: accountController,
                  icon: XImage.loginAccount,
                  hint: '请输入账号',
                ),
                const SizedBox(height: 10),
                XTextField.input(
                    onChanged: (value) {
                      allowLogin();
                    },
                    controller: passWordController,
                    icon: XImage.loginSecret,
                    hint: '请输入密码',
                    obscureText: passwordUnVisible,
                    action: IconButton(
                        alignment: Alignment.centerRight,
                        padding: const EdgeInsets.only(right: 10),
                        onPressed: () {
                          showPassWord();
                        },
                        icon: Icon(
                          passwordUnVisible
                              ? Icons.visibility_off
                              : Icons.visibility,
                          size: 24.w,
                          color: Colors.grey,
                        ))),
                const SizedBox(height: 20),
                ClauseWidget(
                    isSelected: agreeTerms,
                    changed: (v) {
                      changeAgreeTerms();
                    }),
                const SizedBox(height: 10),
                loginSubmit(),
                _jumpButton(),
                const SizedBox(height: 20),
                thirdLoginPlatform(),
              ],
            ))
        : SizedBox(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                XTextField.input(
                  onChanged: (value) {
                    allowLogin();
                  },
                  controller: phoneNumberController,
                  icon: XImage.loginAccount,
                  hint: '请输入手机号',
                ),
                const SizedBox(height: 10),
                XTextField.input(
                  onChanged: (value) {
                    allowLogin();
                  },
                  controller: verifyController,
                  icon: XImage.loginSecret,
                  hint: '请输入验证码',
                  action: Container(
                    padding: const EdgeInsets.only(bottom: 5),
                    child: verificationCodeCountDown(),
                  ),
                ),
                const SizedBox(height: 20),
                ClauseWidget(
                    isSelected: agreeTerms,
                    changed: (v) {
                      changeAgreeTerms();
                    }),
                const SizedBox(height: 10),
                loginSubmit(),
                _jumpButton(),
                const SizedBox(height: 20),
                thirdLoginPlatform(),
              ],
            ),
          );
  }

  Widget _jumpButton() {
    return Container(
      height: 50,
      padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(
              child: GestureDetector(
            onTap: () {
              register();
            },
            child: const Text(
              "注册用户",
              style: TextStyle(color: XColors.themeColor),
            ),
          )),
          Container(
            padding: const EdgeInsets.only(right: 5),
            child: GestureDetector(
              onTap: () {
                forgotPassword(accountController.text);
              },
              child: const Text(
                "忘记密码",
                style: TextStyle(color: XColors.themeColor),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget verificationCodeCountDown() {
    TextStyle textStyle = TextStyle(color: XColors.themeColor, fontSize: 20.sp);
    String text = '发送验证码';
    if (startCountDown) {
      textStyle = TextStyle(color: Colors.grey, fontSize: 18.sp);
      text = "$countDown秒后重新发送";
    }
    return GestureDetector(
        onTap: () {
          if (!sendVerify) {
            sendLoginVerify();
          }
          setState(() {});
        },
        child: Text(
          text,
          textAlign: TextAlign.end,
          style: textStyle,
        ));
  }

  //是否允许点击登录
  void allowLogin() {
    if (accountLogin) {
      allowCommit = (accountController.text.isNotEmpty &&
          passWordController.text.isNotEmpty);
    }
    if (phoneNumberLogin) {
      allowCommit = (phoneNumberController.text.isNotEmpty &&
          verifyController.text.isNotEmpty &&
          verifyController.text.length == 6);
    }
    setState(() {});
  }

  void showPassWord() {
    passwordUnVisible = !passwordUnVisible;
    setState(() {});
  }

  void switchMode(int x) {
    if (x == 1) {
      accountLogin = true;
      phoneNumberLogin = false;
    } else {
      accountLogin = false;
      phoneNumberLogin = true;
    }
    setState(() {});
  }

  void changeAgreeTerms() {
    agreeTerms = !agreeTerms;
    Storage.setBool('agreeTerms', agreeTerms);
    setState(() {});
  }

  void login() async {
    if (accountController.text.isEmpty || passWordController.text.isEmpty) {
      ToastUtils.showMsg(msg: "账号或密码不能为空");
      return;
    }
    // else if (!agreeTerms.value) {
    //   ToastUtils.showMsg(msg: "请阅读并同意服务条款与隐私条款");
    //   return;
    // }
    LoadingDialog.showLoading(context, msg: "登录中...");

    var res = await relationCtrl.provider.login(
      accountController.text,
      passWordController.text,
    );
    if (res.success) {
      LoadingDialog.dismiss(context);
      // Navigator.push(context,
      //     MaterialPageRoute(builder: (context) => const LoginTransPage()));
      RoutePages.to(context: context, path: Routers.logintrans);
      ToastUtils.showMsg(msg: "登录成功");
      [Permission.notification].request();
      Storage.setList(
          Constants.account, [accountController.text, passWordController.text]);
      // Future.delayed(const Duration(seconds: 2));
    } else if (res.code == 400 && res.msg == "认证失败，请重试。") {
      LoadingDialog.dismiss(context);
      ToastUtils.showMsg(msg: '账户名或密码错误');
    } else {
      LoadingDialog.dismiss(context);
      ToastUtils.showMsg(msg: res.msg ?? '登录失败');
    }
  }

  //验证码登录
  void verifyCodeLogin() async {
    if (phoneNumberController.text.isEmpty) {
      ToastUtils.showMsg(msg: "手机号不得为空");
      return;
    }
    if (verifyController.text.isEmpty) {
      ToastUtils.showMsg(msg: "验证码不得为空");
      return;
    }

    LoadingDialog.showLoading(context, msg: "登录中...");

    var res = await relationCtrl.provider.verifyCodeLogin(
        phoneNumberController.text, verifyController.text, dynamicId);
    if (res.success) {
      LoadingDialog.dismiss(context);
      dynamicId = '';
      ToastUtils.showMsg(msg: "登录成功");
      // [Permission.storage, Permission.notification].request();
      Storage.setList(
          Constants.account, [accountController.text, passWordController.text]);
      Navigator.push(context,
          MaterialPageRoute(builder: (context) => const LoginTransPage()));
      // offAndToNamed(Routers.logintrans, arguments: true);
      // Future.delayed(const Duration(seconds: 2));
    } else {
      ToastUtils.showMsg(msg: res.msg ?? '登录失败');
    }
  }

  // void sendVerify() {
  //   RegExp regex = RegExp(Constants.accountRegex);
  //   if (!regex.hasMatch(phoneNumberController.text)) {
  //     ToastUtils.showMsg(msg: "请输入正确的手机号");
  //   }

  //   if (!agreeTerms.value) {
  //     ToastUtils.showMsg(msg: "请同意服务条款与隐私条款");
  //     return;
  //   }
  //   toNamed(Routers.verificationCode,
  //       arguments: {"phoneNumber": phoneNumberController.text});
  // }

  ///验证码登录获取验证码
  Future<void> sendLoginVerify() async {
    RegExp regex = RegExp(Constants.accountRegex);
    if (!regex.hasMatch(phoneNumberController.text)) {
      ToastUtils.showMsg(msg: "请输入正确的手机号");
      return;
    }
    if (sendVerify) {
      ToastUtils.showMsg(msg: "验证码已发送，请稍后再试");
      return;
    }

    startCountDown = true;
    countDown = 60;
    dynamicId = '';
    var res = await relationCtrl.auth.dynamicCode(DynamicCodeModel.fromJson({
      'account': phoneNumberController.text,
      'platName': '资产共享云',
      'dynamicId': '',
    }));

    if (res.success && res.data != null) {
      dynamicId = res.data!.dynamicId;
      sendVerify = true;
    }
    startCountDownMethod();
  }

  void forgotPassword(String account) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => ForgotPasswordPage(
                  account: account,
                )));
  }

  void register() {
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => const RegisterPage()));
  }

  void startCountDownMethod() {
    if (timer != null) {
      if (timer!.isActive) {
        timerClose();
      }
    }
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countDown <= 0) {
        timerClose();
      }
      countDown--;
    });
  }

  void timerClose() {
    timer?.cancel();
    timer = null;
    startCountDown = false;
    countDown = 60;
    sendVerify = false;
  }
}
